#pragma once
#include <string>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <functional>
const int defaultfd = -1;

using func_t = std::function<std::string(const std::string&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
            : _sockfd(defaultfd),
            _port(port),
            _isRunning(false),
            _func(func)
    {
    }
    void Init()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "create socket failed" << std::endl;
            exit(1);
        }
        std::cout << "create socket success" << std::endl;
        // 2. 绑定socket信息，ip和端口
        // 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local,sizeof(local));//local结构体所有字节初始化为0
        local.sin_family = AF_INET;
        //本地格式->网络序列
        local.sin_port = htons(_port);
        //将服务器的套接字绑定到本机所有可用网络接口（网卡）的任意IP地址上
        local.sin_addr.s_addr = INADDR_ANY;
        //那么为什么服务器端要显式的bind呢？IP和端口必须是众所周知且不能轻易改变的！
        //套接字与特定的网络地址
        int n = bind(_sockfd,(struct sockaddr *)&local,sizeof local);
        if(n < 0)
        {
            std::cout << "bind failed" << std::endl;
            exit(2);
        }
        std::cout << "bind success, sockfd : " << _sockfd << std::endl;
    }
    void Start()
    {
        _isRunning = true;
        while(_isRunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //使用recv或recvfrom函数的返回值来确定实际接收的字节数
            //收
            ssize_t s = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*) &peer,&len);
            if(s > 0)
            {
                //将16位无符号整数从网络序转为主机序
                int peer_port = ntohs(peer.sin_port);
                std::string peer_ip = inet_ntoa(peer.sin_addr);
                buffer[s] = 0;
                std::string result = _func(buffer);
                std::cout << "[" << peer_ip << ":" << peer_port<< "]# " << buffer << std::endl;
                //发
                sendto(_sockfd,result.c_str(),result.size(),0,(struct sockaddr*)&peer,len);
            }
        }
    }
private:
    int _sockfd;
    uint16_t _port;
    bool _isRunning;
    func_t _func;// 服务器的回调函数，用来进行对数据进行处理
};